/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.IncubatorLog;
import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.repository.LabRepository;
import me.zhengjie.modules.biz.service.dto.IncubatorDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.IncubatorLogRepository;
import me.zhengjie.modules.biz.service.IncubatorLogService;
import me.zhengjie.modules.biz.service.dto.IncubatorLogDto;
import me.zhengjie.modules.biz.service.dto.IncubatorLogQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.IncubatorLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class IncubatorLogServiceImpl implements IncubatorLogService {

    private final IncubatorLogRepository incubatorLogRepository;
    private final IncubatorLogMapper incubatorLogMapper;
    private final LabRepository labRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String,Object> queryAll(IncubatorLogQueryCriteria criteria, Pageable pageable){
        Page<IncubatorLog> page = incubatorLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<IncubatorLogDto> dto = page.map(incubatorLogMapper::toDto);
        List<IncubatorLogDto> resultDto = dto.getContent();
        for (IncubatorLogDto incubatorLogDto:resultDto) {
            Lab lab = labRepository.findById(incubatorLogDto.getLabId()).orElseGet(Lab::new);
            User user = userRepository.findById(Long.valueOf(incubatorLogDto.getAdministrator())).orElseGet(User::new);
            incubatorLogDto.setLabName(lab.getName());
            incubatorLogDto.setAdministratorName(user.getUsername());
        }
        return PageUtil.toPage(dto);

    }

    @Override
    public List<IncubatorLogDto> queryAll(IncubatorLogQueryCriteria criteria){
        List<IncubatorLog> incubatorLogList = incubatorLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        List<IncubatorLogDto> incubatorLogDtoList = incubatorLogMapper.toDto(incubatorLogList);
        for (IncubatorLogDto incubatorLogDto : incubatorLogDtoList) {
            Lab lab = labRepository.findById(incubatorLogDto.getLabId()).orElseGet(Lab::new);
            User user = userRepository.findById(Long.valueOf(incubatorLogDto.getAdministrator())).orElseGet(User::new);
            incubatorLogDto.setLabName(lab.getName());
            incubatorLogDto.setAdministratorName(user.getUsername());
        }
        return incubatorLogDtoList;
    }

    @Override
    @Transactional
    public IncubatorLogDto findById(Integer id) {
        IncubatorLog incubatorLog = incubatorLogRepository.findById(id).orElseGet(IncubatorLog::new);
        ValidationUtil.isNull(incubatorLog.getId(),"IncubatorLog","id",id);
        return incubatorLogMapper.toDto(incubatorLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IncubatorLogDto create(IncubatorLog resources) {
        return incubatorLogMapper.toDto(incubatorLogRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(IncubatorLog resources) {
        IncubatorLog incubatorLog = incubatorLogRepository.findById(resources.getId()).orElseGet(IncubatorLog::new);
        ValidationUtil.isNull( incubatorLog.getId(),"IncubatorLog","id",resources.getId());
        incubatorLog.copy(resources);
        incubatorLogRepository.save(incubatorLog);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            incubatorLogRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<IncubatorLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (IncubatorLogDto incubatorLog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", incubatorLog.getName());
            map.put("实验室", incubatorLog.getLabName());
            map.put("负责人", incubatorLog.getAdministratorName());
            if (incubatorLog.getTemperature() != null) {
                map.put("温度", incubatorLog.getTemperature() + "℃");
            } else {
                map.put("温度", "--℃");
            }
            if (incubatorLog.getTemperatureThresholdValue() != null) {
                map.put("温度阈值", incubatorLog.getTemperatureThresholdValue() + "℃");
            } else {
                map.put("温度阈值", "--℃");
            }
            map.put("报警信息", incubatorLog.getErrorMessage());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
